package com.wtao.testcamera.utils;

import android.content.Context;
import android.util.Log;

import com.wtao.testcamera.ffmpeg.FFmpegManager;
import com.wtao.testcamera.strategy.RecordStrategy;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class RecordManager {
    private static final String TAG = "RecordManager";
    private static final SimpleDateFormat mDateTimeFormat;
    private String RECORD_CACHE_DIR;
    private final int maxCacheCount = 2;
    private long currentVideoStartRecordTime = 0L;
    private long currentVideoLength = 0L;
    private static RecordManager instance;
    private RecordStrategy recordStrategy;
    private final IVideoEncoder videoEncoder = new VideoEncoderAsyncImpl();
    private final Timer recordTimer = new Timer();
    private TimerTask recordTimerTask;
    private final List<String> videoPathList = new ArrayList();

    public static RecordManager getInstance() {
        if (instance == null) {
            Class var0 = RecordManager.class;
            synchronized(RecordManager.class) {
                if (instance == null) {
                    instance = new RecordManager();
                }
            }
        }

        return instance;
    }

    private RecordManager() {
    }

    public void init(Context context, RecordStrategy recordStrategy) {
        Log.i("RecordManager", "init");
        this.recordStrategy = recordStrategy;
        this.RECORD_CACHE_DIR = context.getExternalFilesDir((String)null).getAbsolutePath() + "/CarCacheVideo";
        this.deleteDir(this.RECORD_CACHE_DIR);
    }

    public void unInit() {
        this.deleteDir(this.RECORD_CACHE_DIR);
    }

    public void start() {
        Log.i("RecordManager", "start");
        this.videoPathList.clear();
        this.startRecord();
        if (this.recordStrategy.isContinuousRecord()) {
            this.recordTimerTask = new TimerTask() {
                public void run() {
                    RecordManager.this.stopRecord();
                    RecordManager.this.startRecord();
                }
            };
            this.recordTimer.schedule(this.recordTimerTask, this.recordStrategy.getRecordMaxTime(), this.recordStrategy.getRecordMaxTime());
        }

    }

    public void encodeFrame(byte[] data) {
        this.videoEncoder.encode(data, System.nanoTime() / 1000L);
    }

    public void stop() {
        Log.e("RecordManager", "stop");
        this.recordTimerTask.cancel();
        this.stopRecord();
        if (this.videoPathList.size() == 1) {
            File file = new File((String)this.videoPathList.get(0));
            File finalFile = this.getCaptureFile(this.recordStrategy.getVideoDir());
            if (file == null || finalFile == null) {
                return;
            }

            file.renameTo(finalFile);
            Log.e("RecordManager", "save video file: " + finalFile.getAbsolutePath());
        } else {
            this.mergeVideo();
        }

    }

    private void startRecord() {
        Log.i("RecordManager", "startRecord");
        this.currentVideoStartRecordTime = System.currentTimeMillis();
        File file = this.getCaptureFile(this.RECORD_CACHE_DIR);
        this.videoPathList.add(file.getAbsolutePath());
        Log.e(TAG, "  startRecord init初始化");
        this.videoEncoder.init(file.getAbsolutePath(), this.recordStrategy.getVideoWidth(), this.recordStrategy.getVideoHeight(), this.recordStrategy.getFrameRate(), this.recordStrategy.getBitRate());
        this.videoEncoder.start();
    }

    private void stopRecord() {
        Log.i("RecordManager", "stopRecord");
        this.currentVideoLength = System.currentTimeMillis() - this.currentVideoStartRecordTime;
        this.videoEncoder.stop();
        this.videoEncoder.release();
        if (this.videoPathList.size() > 2) {
            File file = new File((String)this.videoPathList.get(0));
            if (file.exists()) {
                file.delete();
            }

            this.videoPathList.remove(0);
        }

    }

    private void mergeVideo() {
        Log.i("RecordManager", "mergeVideo");

        while(this.videoPathList.size() > 2) {
            String path = (String)this.videoPathList.remove(0);
            File file = new File(path);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
        }

        File file = this.getCaptureFile(this.RECORD_CACHE_DIR);
        FFmpegManager.getInstance().concatVideo(this.videoPathList, file.getAbsolutePath());
        FFmpegManager.getInstance().clipVideo(this.currentVideoLength, this.currentVideoLength + this.recordStrategy.getRecordMaxTime(), file.getAbsolutePath(), this.getCaptureFile(this.recordStrategy.getVideoDir()).getAbsolutePath());
    }

    private File getCaptureFile(String dirName) {
        File dir = new File(dirName);
        Log.i("RecordManager", "path=" + dir);
        dir.mkdirs();
        if (dir.canWrite()) {
            return new File(dir, this.getDateTimeString() + ".mp4");
        } else {
            Log.e("RecordManager", "getCaptureFile: dir can't write\n" + dir);
            return null;
        }
    }

    private boolean deleteDir(String path) {
        File file = new File(path);
        if (!file.exists()) {
            System.err.println("The dir are not exists!");
            return false;
        } else {
            String[] content = file.list();
            String[] var4 = content;
            int var5 = content.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                String name = var4[var6];
                File temp = new File(path, name);
                if (temp.isDirectory()) {
                    this.deleteDir(temp.getAbsolutePath());
                    temp.delete();
                } else if (!temp.delete()) {
                    System.err.println("Failed to delete " + name);
                }
            }

            return true;
        }
    }

    private String getDateTimeString() {
        GregorianCalendar now = new GregorianCalendar();
        return mDateTimeFormat.format(now.getTime());
    }

    static {
        mDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US);
    }
}
